/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <string.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart2;
DMA_HandleTypeDef hdma_usart2_rx;
DMA_HandleTypeDef hdma_usart2_tx;

/* USER CODE BEGIN PV */
uint8_t ctrlLED[2];
uint8_t Rcv[50];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint8_t msg[] = "helloworld";
GPIO_PinState state = GPIO_PIN_SET;

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
 {
//	  HAL_UART_Transmit_IT(&huart2,ctrlLED, 2);
	 HAL_UART_Transmit_DMA(&huart2,ctrlLED, 2);
	  if(ctrlLED[1] == '0')
	  {
		  state = GPIO_PIN_RESET;
	  }
	  else
	  {
		  state = GPIO_PIN_SET;
	  }
	  if(ctrlLED[0] == 'R')
	  {
		  HAL_GPIO_WritePin(LED_RED_GPIO_Port,LED_RED_Pin, state);
	  }
	  else if(ctrlLED[0] == 'G')
	  {
		  HAL_GPIO_WritePin(LED_GREEN_GPIO_Port,LED_GREEN_Pin, state);
	  }
	  else if(ctrlLED[0] == 'B')
	  {
		  HAL_GPIO_WritePin(LED_BLUE_GPIO_Port,LED_BLUE_Pin, state);
	  }
	  //HAL_UART_Receive_IT(huart,ctrlLED, 2);
	  HAL_UART_Receive_DMA(huart,ctrlLED, 2);
 }
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	// 使用中断的好习惯：判断串口是否是此串口
	if(huart == &huart2)
	{
		HAL_UART_Transmit_DMA(huart, Rcv, 50);

	}
	HAL_UARTEx_ReceiveToIdle_DMA(huart, Rcv, 50);
	__HAL_DMA_DISABLE_IT(&hdma_usart2_rx,DMA_IT_HT);
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
  //HAL_UART_Receive_DMA(&huart2,ctrlLED, 2);
  HAL_UARTEx_ReceiveToIdle_DMA(&huart2, Rcv, sizeof Rcv);
  __HAL_DMA_DISABLE_IT(&hdma_usart2_rx,DMA_IT_HT);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	  /*
	   * 一、基本需求
	   * 1. 先实现 每秒板子向屏幕输出信息 Transmit
	   * 	第三个参数是超过时间 可以理解为倒计时
	   * 	-- 1. 如何将STM32与电脑连接？
	   * 		TTL转->USB;
	   */
//	  HAL_UART_Transmit(&huart2, msg,strlen(msg), 100);
//	  HAL_Delay(1000);
	  /*
	   * 2. 然后实现，由键盘向STM32输入，然后STM32接收 Receive
	   * 	第三个参数 HAL_MAX_DELAY
	   */
//	  HAL_UART_Receive(&huart2, msg, 2, HAL_MAX_DELAY);
//	  HAL_UART_Transmit(&huart2, msg,2, 100);
	  /*
	   * 3. 最后实现我们的目的：
	   * 	通过键盘输入来控制灯的亮灭 传输两个字节的数据——灯 亮/灭
	   *
	   */


	  // 二、 三大模式
	  // 轮询方式 ： 阻塞 和 定长
	  /*
	   * 串口的中断模式：
	   * 打开uart2的中断模式，然后使用中断处理函数。
	   * 定义Rx_CpltCallback函数
	   *
	   * -- 1. 为什么没有接收到数据？
	   * -- 2. 且灯没亮？
	   * 因为回调函数应该定义在main外 变量定义成全局
	   */
	  /*
	   * 串口DMA模式：串口接收不定长数据，进一步减少CPU占用
	   * 1）DMA模式
	   * 	DMA通道创建
	   * 	函数调用: 即使使用了DMA，其实还是有中断参与其中的。只不过DMA是DMA传输完成中断
	   * 2) DMA + 不定长数据（串口扩展函数）
	   * 	HAL_UARTEx_ReceiveToIdle_DMA
	   * 	写法：在it.c里找到串口中断 然后点进调用的函数里 找到RxEventCallback函数
	   * 	-- 1.联系：原先我们找到中断 是直接在中断执行我们的逻辑
	   * 	 	  而此处，我们需要先确认接收（这一中断完成，其实就是接收本身），在回调里面执行我们的逻辑。所以我们的逻辑代码是放在回调里面。
	   * 	 	  stm32f1xx_it.c -> void USART2_IRQHandler(void) ->HAL_UART_IRQHandler(&huart2)->
	   * 	 	  __weak void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
	   * 	 细节： 使用中断的好习惯
	   * 	 		扩展函数也有DMA，但是有个过半中断的弊端。
	   * 	 		关闭DMA过半中断的方式：__HAL_DMA_DISABLE_IT(DMA通道地址&hdma……，DMA中断);
	   * 此时不会调用Rx_CpltCallback，说明没有去执行HAL_UART_Receive_DMA(&huart2,ctrlLED, 2);
	   *
	   */
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Channel6_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn);
  /* DMA1_Channel7_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel7_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel7_IRQn);

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  /* USER CODE BEGIN MX_GPIO_Init_1 */

  /* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, LED_BLUE_Pin|LED_GREEN_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED_RED_GPIO_Port, LED_RED_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pins : LED_BLUE_Pin LED_GREEN_Pin */
  GPIO_InitStruct.Pin = LED_BLUE_Pin|LED_GREEN_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pin : LED_RED_Pin */
  GPIO_InitStruct.Pin = LED_RED_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED_RED_GPIO_Port, &GPIO_InitStruct);

  /* USER CODE BEGIN MX_GPIO_Init_2 */

  /* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
